package com.youxin.foundation.db.utils;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.youxin.foundation.utils.ClassUtils;

/**
 * Table工具类方法
 * 
 * @author yingde.cao
 *
 */
public class TableUtils {

	public static <T> List<T> resultSetToList(ResultSet rs, Class<?> cls) throws Exception {		
		List<T> list = new ArrayList<>();		
		T obj = null;
		while (rs.next()) {
			obj = resultSetToBean(rs,cls);
			list.add(obj);
		}
		return list;
	}

	public static  <T> T  resultSetToBean(ResultSet rs, Class<?> cls) throws Exception {
		Method[] methods = cls.getMethods();
		return resultSetToBean(rs, cls, methods);
	}

	private static <T> T resultSetToBean(ResultSet rs, Class<?> cls, Method[] methods) throws Exception {
		ResultSetMetaData meta = rs.getMetaData();
		T obj = ClassUtils.instance(cls);
		for (int i = 1; i <= meta.getColumnCount(); i++) {
			String colName = meta.getColumnName(i);
			colName=colName.replace("_", "");
			String setMethodName = "set" + colName;
			Method setMethod = null;
			for (int j = 0; j < methods.length; j++) {
				if (methods[j].getName().equalsIgnoreCase(setMethodName)) {
					setMethodName = methods[j].getName();
					setMethod = methods[j];
					Object value = rs.getObject(colName);
					if (value == null) {
						continue;
					}
					try {
						/**
						 * 利用反射获取对象,JavaBean内部属性和ResultSet中一致时候
						 */
						setMethod.invoke(obj, value);
						break;

					} catch (Exception e) {
						/**
						 * JavaBean内部属性和ResultSet中不一致时候，使用String来输入值。
						 */
						setMethod.invoke(obj, value.toString());
					}
				}
			}
		}
		return obj;
	}
}